const fs = require('fs');
const mysql2 = require('mysql2');

const connection = mysql2.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'test'
})
module.exports = {
  async addFile(request) {
    let { pname } = request.body;
    const uploadFile = request.files.uploadFile;
    if (uploadFile.size > 0) {
      // 转存到指定文件夹
      if (!fs.existsSync('static/uploads')) {
        fs.mkdirSync('static/uploads');
      }
      let tempPath = uploadFile.path;
      fs.writeFileSync('static/uploads/' + uploadFile.name, fs.readFileSync(tempPath));
      let fileUrl = '/uploads/' + uploadFile.name
      // 把数据添加到数据库
      let [rows] = await connection.promise().query('INSERT INTO products(img, pname) VALUES(?,?)', [fileUrl, pname]);

      return rows;
    }
  }
}